/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution {
public:
    Node* connect(Node* root) {
        queue<Node*> queueNode;
        if (root == NULL) {
            return root;
        }

        queueNode.push(root);
        Node* preFront = NULL;
        Node* curFront = NULL;
        Node* preHead = NULL;
        bool flag = false;
        while (!queueNode.empty()) {
            preFront = queueNode.front();
            if (!flag) {
                preHead = preFront;
                flag = true;
            }
            queueNode.pop();
            /* 操作 */
            if (!queueNode.empty()) {
                curFront = queueNode.front();
                preFront->next = curFront;
            } else {
                flag = false;
            }
            while ((!flag) &&(preHead != NULL)) { // 此处，分层实现的不是很好，应该用队列大小来实现。
            /* 向队列添加下一层节点 */
                if (preHead->left != NULL) {
                    queueNode.push(preHead->left);
                }
                if (preHead->right != NULL) {
                    queueNode.push(preHead->right);
                }
                preHead = preHead->next;
            }
        }
        return root;
    }
};